/**
 * @author banglong
 * @date 2016/8/22.
 */
require(['avalon', 'jquery', 'es5_sham', 'Layer', 'layPage', 'tools', 'indexApi', 'rootPath', 'BillList', 'Ygsq',
        'GoodsQuery', 'stockSearch', 'booksApplyAnalyze', 'CardManager', 'RTStoreQuery', 'tableFixed',
        'ChangePassword', 'AccountQuery', 'billListActions', 'polyfill', 'accountQueryActions',
        'bootstrap'
    ],
    function(avalon, $, es5_sham, layer, layPage, tools, api, rootPath, BillList, Ygsq, GoodsQuery, stockSearch,
        booksApplyAnalyze, CardManager, RTStoreQuery, tableFixed, ChangePassword, AccountQuery) {
        layer.config({
            path: rootPath.getRootPath() + 'js/common/layer/'
        });
        // 定义全局常用变量 avalon jquery 方便访问
        window.avalon = avalon;
        window.JQuery = window.$ = $;
        window.layPage = layPage
        window.cache = {};
        var userDeps = JSON.parse(localStorage.getItem("userDeps"))
            // 节点树 用于保存被替换的节点 常用在第一个界面为列表 第二个界面为 新建或者修改界面使用
            // 在 showMenu watch 方法中被清空
        window.documentNodeTree = [];

        //通知卡片
        $('.ic-close,.msg-btn').on('click', function() {
            var result = [];
            result = indexVm.cartNotice.$model;
            for (var i = 0; i < result.length; i++) {
                result[i].Status = false;
                //result[i].CardNumber = $.trim(result[i].CardNumber);
            };
            //console.log(result)
            api.modifyDisCardReason({
                className: 'CardManager',
                method: 'UpdateDisCardReasonStatus',
                disCardReasonInfo: JSON.stringify(result)
            }).then(function(jsonResult) {
                if (jsonResult.issuccess === 0) {
                    $(".shadow").hide();
                    $(".msg-container").slideUp();
                    sessionStorage.setItem('noticeFlag', true);
                }
            })
            $(".shadow").hide();
            $(".msg-container").slideUp();
            sessionStorage.setItem('noticeFlag', true);

        })
        $('body').on('click', '#closeStock', function() {

                $('.shadow').hide();
                $('#stockPopup').hide();

            })
            // 按 esc 键退出所有的 弹出框
        $('body').on('keydown', function(e) {
            if (e.keyCode !== 27) return;
            layer.closeAll();
        });

        var user = JSON.parse(localStorage.getItem('currentUser')) || {};
        window.cache.user = user;
        var allMenu = {};
        var $main = $('#main');
        var deptInfo; //当前科室
        // 定义 avalon 对象 路径导航
        var indexVm = avalon.define({
            $id: 'nav',
            firstMenu: [], //一级菜单
            secondMenu: [], //二级菜单
            thirdMenu: [], //三级菜单
            chooseFirstIndex: 0, // 一级菜单 index 用于控制是否显示激活图标
            chooseSecondIndex: 0, // 二级菜单index
            cartNotice: [], //卡片提醒	
            breadcrumb: '', //面包屑 路径导航 只有第三级菜单才有用
            showMenu: true,
            user: user,
            deptInfo: {
                Ksmc: ''
            },
            imgWidth: '100%',
            // 点击第一级菜单
            handleClickFirstMenu: function(event, index) {

                event.preventDefault();
                indexVm.chooseFirstIndex = index;
                var firstMenuId = indexVm.firstMenu[index].Id;
                var secondMenuId;
                secondMenuId = chooseSecondMenu(allMenu, firstMenuId, secondMenuId); // 取出第二级菜单
                indexVm.chooseSecondIndex = 0; // 上方箭头图标初始化
                chooseThirdMenu(allMenu, secondMenuId); // 取出第三级菜单
            },
            // 点击二级菜单
            handleClickSecondMenu: function(event, index) {
                event.preventDefault();
                indexVm.chooseSecondIndex = index;
                var secondMenuId = indexVm.secondMenu[index].Id;
                chooseThirdMenu(allMenu, secondMenuId);
                if (indexVm.chooseFirstIndex == 1 && indexVm.chooseSecondIndex == 1) //临时需求暂不走系统配置，库房中载入余额查询
                {
                    var htmlStr = '<li><a href="javascript:aaaa()"  title="账户余额查询"><img alt="" src="img/菜单3/报表.ico"><span>账户余额查询</span></a></li>';

                    $('.third-menu>ul').append(htmlStr);

                }
            },
            // 点击三级菜单
            handleClickThirdMenu: function(event, index) {
                event.preventDefault();
                var menu = indexVm.thirdMenu[index];
                var thirdMenuId = indexVm.thirdMenu[index].Id;
                // 设置导航路径
                if (menu.Mlevel === 2) { // 表明刚开始点击 第三级菜单
                    indexVm.breadcrumb = menu.Name;
                } else {
                    indexVm.breadcrumb += '-' + menu.Name;
                }
                // 判断是否还有子菜单
                if (parseInt(menu.Islast) === 0) {
                    chooseThirdMenu(allMenu, thirdMenuId, menu.Mlevel + 1);
                    return;
                }
                // 路径跳转
                switch (menu.Winname) {
                    case 'inventory': //库存警戒值维护
                        //        	getInventory();
                        var param = getMainHandlerInitParam(menu, 7);
                        window.Param = param //科室及菜单信息
                        addIframeToMain({
                            param: param,
                            src: "new/view/inventory.html"
                        });
                        break;
                    case 'consumable': //耗材有效期维护
                        //        	getConsumable();
                        var param = getMainHandlerInitParam(menu, 7);
                        window.Param = param //科室及菜单信息
                        addIframeToMain({
                            param: param,
                            src: "new/view/consumable.html"
                        });
                        break;
                    case 'roommanager': //房间管理
                        var param = getMainHandlerInitParam(menu, 7);
                        window.Param = param //科室及菜单信息
                        addIframeToMain({
                            param: param,
                            src: "new/view/roomManager.html"
                        });
                        break;
                    case 'wtyy': //二级库房 预约情况查询
                        var param = getMainHandlerInitParam(menu, 0);

                        window.Param = param //科室及菜单信息
                        addIframeToMain({
                            param: param,
                            src: "new/view/wtReservationQuery.html"
                        });
                        break;
                    case 'wtly': //二级库房 领用单
                        var param = getMainHandlerInitParam(menu, 0);

                        window.Param = param //科室及菜单信息
                        addIframeToMain({
                            param: param,
                            src: "new/view/collerlist-manager.html"
                        });
                        break;
                    case 'wtlymanage': //设备科领用单管理（零库存）
                        var param = getMainHandlerInitParam(menu, 0);

                        window.Param = param //科室及菜单信息
                        addIframeToMain({
                            param: param,
                            src: "new/view/wtlymanage.html"
                        });
                        break;
                    case 'wtlysearch': //设备科领用单查询（零库存）
                        var param = getMainHandlerInitParam(menu, 0);

                        window.Param = param //科室及菜单信息
                        addIframeToMain({
                            param: param,
                            src: "new/view/collerlist-manager.html"
                        });
                        break;
                    case 'repairmanager': //维修单管理
                        getRepairmanager();
                        break;
                    case 'goodsselect':
                        initGoodsSelect(menu); // 物品查询界面
                        break;
                    case 'stocksearch':
                        initStockSearch(menu); // 初始化科室库存查询页面
                        break;
                    case 'booksapplyanalyze':
                    case 'wardapplyanalyze':
                    case 'packagedrawquery':
                        initBooksApplyAnalyze(menu); // 报表
                        break;
                    case 'cardmanager':
                        initCardManager(menu); //卡片管理
                        break;
                    case 'rtstorequery':
                        initRTStoreQuery(menu); //正式库存查询
                        break;
                    case 'ygsq':
                        initYgsqReceiveReceipt(menu); //初始化阳光申请单
                        break;
                    default:
                        initReceiveReceipt(menu); // 初始化领用单
                        break;
                }
            },
            // 登出
            logout: function() {
                if (confirm("是否要退出当前账号？")) {
                    location.href = 'logout';
                }
            },
            // 修改密码
            changePassword: function() {
                new ChangePassword().init({
                    user: user
                });
            }
        });
        // 扫描
        avalon.scan(document.body);

        // 当 showMenu 为true 移除main的第一个节点 并保存
        indexVm.$watch("showMenu", function(result) {
            if (result) {
                var firstNode = tools.getFirstElementChild($main.get(0));
                if (firstNode) {
                    // 清除内容
                    $main.get(0).removeChild(firstNode);
                    documentNodeTree.splice(0, documentNodeTree.length);
                }
                $(document).trigger('destroy'); // 调用销毁方法
            }
        });

        // 分割字符串 获取 加载参数
        function getOpenParam(OpenparmStr) {
            var Openparm = {
                GoodsBook: '', // 账册
                ProviderDept: '', // 供应科室id
                Authority: [], // 权限
                PackageBigCat: '', // 包大类
                IsQuery: false // 是否是查询界面
            };

            if (!OpenparmStr) {
                return Openparm;
            }

            var arr = OpenparmStr.split('}');
            for (var i = 0; i < arr.length; i++) {
                Object.keys(Openparm).forEach(function(key) {
                    if (arr[i].indexOf(key) !== -1) {
                        if (key === 'IsQuery') {
                            Openparm[key] = arr[i].split(':')[1] === 'true';
                        } else {
                            Openparm[key] = arr[i].split(':')[1];
                        }
                    }
                });
            }
            return Openparm;
        }
        //新增库房&预算管理通用方法
        function addIframeToMain(ops) {
            $('.third-menu').hide();
            var url = rootPath.getRootPath() + ops.src + '?param=' + encodeURI(JSON.stringify(ops.param));
            //$('#main').load(url)

            var height = calcPageHeight()
            var myElement = document.createElement("iframe")
            myElement.src = url;
            myElement.className = "iframeWrap"
            myElement.style.width = "100%";
            myElement.style.height = height + 'px'
            myElement.frameBorder = "0";
            document.getElementById('main').appendChild(myElement);
            myElement.contentWindow["paramFromParent"] = ops.param; //向子窗口传递数据
        }

        function calcPageHeight() {
            var wHeight = $(window).height();
            var mHeight = $('#main').offset().top
            var height = wHeight - mHeight - 10
            return height
        }

        //维修单页面
        function getRepairmanager() {
            var url = rootPath.getRootPath() + 'repairBill/repairBillManager.html';
            var myElement = document.createElement("iframe")
            myElement.src = url;
            myElement.id = "repair-bill-manager";
            myElement.style.width = "100%";
            myElement.style.height = "100%";
            myElement.style.position = "fixed";
            myElement.style.left = "0";
            myElement.style.top = "0";
            myElement.style.zIndex = "90";
            document.body.appendChild(myElement);
            //document.getElementById('main').appendChild(myElement);
        }

        // 初始化 物品查询页面
        function getMainHandlerInitParam(menu, type) {
            indexVm.showMenu = false;
            menu = JSON.parse(JSON.stringify(menu.$model));
            var Openparm = getOpenParam(menu.Openparm);
            var param = {
                breadcrumb: indexVm.breadcrumb,
                Openparm: Openparm,
                showMenu: function() {
                    indexVm.showMenu = true;
                },
                checkBreadcrumb: function() { // 下面 菜单点击返回的时候 需要校验 路径的正确行
                    var breadcrumbs = indexVm.breadcrumb.split('-');
                    for (var i = 0; i < breadcrumbs.length; i++) {
                        if (i === breadcrumbs.length - 1) {
                            return;
                        }
                        if (i === 0) {
                            indexVm.breadcrumb = breadcrumbs[i];
                        } else {
                            indexVm.breadcrumb += '-' + breadcrumbs[i];
                        }
                    }

                }
            };
            switch (type) {
                case 0: // 领用单等单据
                    param = Object.assign({}, param, {
                        InDeptAccountID: deptInfo.DeptAccountID,
                        InDeptAccount: deptInfo,
                        BillType: menu.Winname
                    });

                    break;
                case 1: // 物品查询页面
                    param = Object.assign({}, param, {
                        showAllGoods: false,
                        currentDept: deptInfo
                    });
                    break;
                case 2: // 科室实时库存
                    break;
                case 3: // 报表
                    param = Object.assign({}, param, {
                        reportType: menu.Winname
                    });
                    break;
                case 5: // 正式库存查询
                    param = Object.assign({}, param, {
                        currentDept: deptInfo
                    });
                    break;
                case 6: // 领用单等单据
                    param = Object.assign({}, param, {
                        InDeptAccountID: deptInfo.DeptAccountID,
                        InDeptAccount: deptInfo,
                        BillType: menu.Winname
                    });
                    break;
                case 7:
                    param = Object.assign({}, param, {
                        InDeptAccountID: deptInfo.DeptAccountID,
                        user: user
                    });
                    break;
            }
            return param;
        }

        // 初始化领用单
        function initReceiveReceipt(menu) {

            // 根据不同的单据 类型 跳转到 单界面
            var param = getMainHandlerInitParam(menu, 0);
            var str = new BillList();
            new BillList().init($main, param);
        }

        // init goodsSelect
        function initGoodsSelect(menu) {
            var param = getMainHandlerInitParam(menu, 1);
            new GoodsQuery().init($main, param);
        }

        // 初始化报表查询
        function initStockSearch(menu) {
            var param = getMainHandlerInitParam(menu, 2);
            stockSearch.init($main, param);
        }

        // 单一科室所有账册查询
        function initBooksApplyAnalyze(menu) {
            var param = getMainHandlerInitParam(menu, 3);
            booksApplyAnalyze.init($main, param);
        }

        // 卡片管理
        function initCardManager(menu) {
            var param = getMainHandlerInitParam(menu, 4);
            new CardManager().init($main, param);
        }

        // 正式库存查询
        function initRTStoreQuery(menu) {
            var param = getMainHandlerInitParam(menu, 5);
            new RTStoreQuery().init($main, param);
        }

        // 阳光采购申请单
        function initYgsqReceiveReceipt(menu) {
            // 根据不同的单据 类型 跳转到 单界面
            var param = getMainHandlerInitParam(menu, 6);
            new Ygsq().init($main, param);
            //new BillList().initYgsq($main, param);
        }


        // 加载所有的菜单 从后台加载
        api.getSystemMenu({
            className: 'AuthorizationManager',
            method: 'GetUserModules',
            ygid: user.Ygid,
            opentype: 'WEB'
        }).then(function(jsonResult) {
            if (jsonResult.issuccess !== 0 || jsonResult.result === '[]') {
                return Promise.reject("菜单初始化失败，请联系管理员");
            }

            allMenu = JSON.parse(jsonResult.result); // 得到所有的菜单
            var firstMenuId; // 一级菜单id
            var secondMenuId; // 二级菜单id
            allMenu.forEach(function(data) { // 第一次循环 取出所有的一级菜单
                if (userDeps.IsEjkf && data.Mlevel === 0) {
                    indexVm.firstMenu.push(data);
                } else if (!userDeps.IsEjkf && data.Mlevel === 0) {
                    if (data.Id !== "wt") {
                        indexVm.firstMenu.push(data);
                    }

                }
                if (data.Mlevel === 0) {
                    if (!firstMenuId) {
                        firstMenuId = data.Id;
                    }
                }



            });
            secondMenuId = chooseSecondMenu(allMenu, firstMenuId, secondMenuId); // 取出第二级菜单
            chooseThirdMenu(allMenu, secondMenuId); // 取出第三级菜单

        })['catch'](function(ex) {
            tools.handleError(ex)
        });


        // 获取科室详细信息
        api.getOutDTODept({
            className: 'OrganizationManager',
            method: 'GetOutDTODept',
            ksdm: localStorage.getItem('ksdm')
        }).then(function(jsonResult) {

            if (jsonResult.issuccess === 0) {
                deptInfo = JSON.parse(jsonResult.result);
                indexVm.deptInfo = deptInfo;
                localStorage.setItem('deptInfo', JSON.stringify(deptInfo)); // 保存进本地缓存
                cache.deptInfo = deptInfo; // 全局缓存
                api.getDepAccountByAccountID({
                    className: 'DeptAccountManager',
                    method: 'GetDepAccountByAccountID',
                    deptAccountID: deptInfo.DeptAccountID
                }).then(function(jsonResult) {
                    if (jsonResult.issuccess === 0) {
                        var result = JSON.parse(jsonResult.result);
                        localStorage.setItem('deptAccount', JSON.stringify(result));
                    }
                })
                if (!sessionStorage.getItem('noticeStockFlag')) {
                    getStockWarningReminder(deptInfo.DeptAccountID)
                }


                //卡片通知信息
                if (!sessionStorage.getItem('noticeFlag')) {
                    api.getDisCardReason({
                        className: 'CardManager',
                        method: 'GetDisCardReason',
                        condition: JSON.stringify({ "ColumnName": "DrawDeptAccountID", "FullString": null, "Oper": "Equal", "Value": deptInfo.DeptAccountID, "Type": "String" })
                    }).then(function(jsonResult) {
                        if (jsonResult.issuccess === 0) {
                            var result = JSON.parse(jsonResult.result);
                            for (var i = 0; i < result.length; i++) {
                                if (result[i].Status) {
                                    indexVm.cartNotice.push(result[i]);
                                }
                            }
                            if (indexVm.cartNotice.length > 0) {
                                $(".shadow").show();
                                $(".msg-container").slideDown();
                            }

                        }
                    })
                }

            }
        })['catch'](function(ex) {
            tools.handleError(ex)
        });

        // 取出第二级菜单
        function chooseSecondMenu(allMenu, firstMenuId, secondMenuId) {
            indexVm.secondMenu.splice(0, indexVm.secondMenu.length);
            allMenu.forEach(function(data) { // 第二次循环 取出属于第一级菜单的所有二级菜单
                if (data.Mlevel === 1) { // 二级菜单
                    // /^cs[0-9]{2}$/gm.test('cs01')
                    if (new RegExp('^' + firstMenuId + '[0-9]{2}$', 'gm').test(data.Id)) {
                        indexVm.secondMenu.push(data);
                        if (!secondMenuId) {
                            secondMenuId = data.Id;
                        }
                    }
                }
            });
            return secondMenuId;
        }

        // 三级菜单
        function chooseThirdMenu(allMenu, secondMenuId, level) {

            indexVm.thirdMenu.splice(0, indexVm.thirdMenu.length);
            level = level || 2; //默认为2 表示第三级菜单 如果有值 则表示 可以作为判断标准
            allMenu.forEach(function(data) { // 第三次循环 取出属于第二级菜单的所有三级菜单
                if (data.Mlevel === level) { // 三级菜单
                    if (new RegExp('^' + secondMenuId + '[0-9]{2}$', 'gm').test(data.Id)) {
                        if (!/^wt/.test(data.Winname) || userDeps.IsEjkf) {
                            indexVm.thirdMenu.push(data);
                        }
                    }
                }
            });
            indexVm.showMenu = true;
        }
        //子窗体控制三级菜单显示
        window.showMenuFn = function() {
                indexVm.showMenu = true
                var breadcrumbs = indexVm.breadcrumb.split('-')
                breadcrumbs.pop();
                indexVm.breadcrumb = breadcrumbs.join('-')
            }
            //获取本科室库存警戒值
        function getStockWarningReminder(deptAccountID) {
            api.getStockWarningReminder({
                className: 'TwoLevelStockManager',
                method: 'GetStockWarningReminder',
                deptAccountID: deptAccountID
            }).then(function(jsonResult) {
                if (jsonResult.issuccess === 0) {
                    var result = JSON.parse(jsonResult.result);
                    if (result && result.length > 0) {
                        sessionStorage.setItem('noticeStockFlag', true)
                        kcjgLayer(result)
                    }
                }
            })
        }
        //库存警告提示
        function kcjgLayer(data) {
            layer.open({
                title: '消息提醒',
                offset: 'rb',
                btn: ['查看', '取消'],
                shade: 0,
                content: '有物品低于库存，请尽快处理',
                yes: function(index, layero) {
                    //按钮【按钮一】的回调
                    $('.shadow').show();
                    $('#stockPopup').show();
                    stockHtml(data);
                    layer.close(index);
                },
                btn2: function(index, layero) {
                    //按钮【按钮二】的回调

                    //return false 开启该代码可禁止点击该按钮关闭
                }
            });
        }

        //警戒值模板
        function stockHtml(data) {
            if (!data || data.length == 0) {
                return false;
            }
            $('#stockPopup').empty();
            var html = ''
            html += "<div class='title clearfix'><span>消息列表</span> <em id='closeStock'>X</em></div>"
            html += '<div style="height: 465px;overflow:  auto;"><table  style="width: 100%">'
            html += '<tr><th>物品名称</th><th>物品代码</th><th>当前库存</th><th>警戒值</th></tr>'
            for (var i = 0; i < data.length; i++) {
                html += '<tr>'
                html += '<td>' + data[i].GoodsName + '</td>'
                html += '<td>' + data[i].GoodsCode + '</td>'
                html += '<td>' + data[i].WarnType + '</td>'
                html += '<td>' + data[i].WarnValue + '</td>'
                html += '</tr>'
            }

            html += '</table></div>'
            $('#stockPopup').html(html)
        }



        function aaaa() {
            alert(1);
            $main.load("/web/html/balanceQuery.html");
        }

    });